<?php

namespace App\Api\Controllers\CustomerApplets;

use App\Models\CustomerAppletsStore;
use App\Models\MerchantStoreAppidSecret;
use App\Models\Store;
use App\Models\WechatThirdConfig;
use function GuzzleHttp\Psr7\str;
use Illuminate\Http\Request;
use App\Api\Controllers\CustomerApplets\BaseController;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use EasyWeChat\Factory;
use EasyWeChat\OpenPlatform\Server\Guard;
use Illuminate\Support\Facades\DB;
use App\Api\Controllers\CustomerApplets\AliPayTicketController;

class WechatTicketController extends BaseController
{

    protected $customerAppletsRegisterWeApps = "customerapplets_fast_register_weapps";

    protected $customerAppletsAuthorizeAppid = "customerapplets_authorize_appids";

    // //第三方开放平台appid
    // protected $app_id;
    // //第三方开放平台secret
    // protected $secret;
    // //第三方开放平台token
    // protected $token;
    // //第三方开放平台aes_key
    // protected $aes_key;
    // //域名
    // protected $domain;
    // //微信公众号的appid
    // protected $weChatServerAppId;
    // //微信公众号的秘钥
    // protected $weChatServerSecret;
    //
    // public function __construct()
    // {
    //
    //     // $this->app_id  = config('api.app_id');
    //     $model = new WechatThirdConfig();
    //     $data = $model->getInfo();
    //     $this->app_id = $data->app_id;
    //     // $this->secret  = config('api.secret');
    //     $this->secret  = $data->app_secret;
    //     $this->token   = config('api.token');
    //     $this->aes_key = config('api.aes_key');
    //     $this->domain  = env('APP_URL');
    //     $this->weChatServerAppId   = config('api.weChatServerAppId');
    //     $this->weChatServerSecret  = config('api.weChatServerSecret');
    // }

    /**
     * 处理上传文件，进行到微信处理（添加到临时素材）
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function uploadFile(Request $request){
        $file = $request->file("file");
        $extension = $file->getClientOriginalExtension();
        $filename = date('YmdHis', time()).$this->uuid().'.'.$extension;
        $path = $file->storeAs('/upload/storeLicense', $filename, 'admin');
        $path = env("APP_URL")."/".$path;
        //转换成服务器的绝对路径
        $file_path = str_replace(env('APP_URL'), public_path(), $path);
        if($path){
            $config = [
                'app_id' => $this->weChatServerAppId,
                'secret' => $this->weChatServerSecret,
                'response_type' => 'array',
            ];
            $app = Factory::officialAccount($config);
            $result = $app->media->uploadImage($file_path);
            if(!empty($result['media_id']) && isset($result['media_id'])){
                $result['path'] = $path;
                return $this->responseDataJson(200,"上传成功",$result);
            }else{
                return $this->responseDataJson(202,"上传临时素材失败",$path);
            }
        }else{
            return $this->responseDataJson(202,"上传失败",$path);
        }
    }

    /**
     * 消息与事件接收URL接收到消息的处理
     * @param $appid
     * @param Request $request
     * @return string
     */
    public function message($appid,Request $request){
        Log::info("消息与事件接收URL以下：");
        Log::info($appid);
        $requestAllRequest = $request->all();
        $requestAllData    = $request->getContent();
        Log::info("数组数据：".json_encode($requestAllRequest));
        Log::info("xml数据：".$requestAllData);
        return "success";
    }

    /**
     * 接收微信的授权通知
     * 验证票据（component_verify_ticket），在第三方平台创建审核通过后，
     * 微信服务器会向其 ”授权事件接收URL” 每隔 10 分钟以 POST 的方式推送component_verify_ticket
     * 接收 POST 请求后，只需直接返回字符串 success
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function getTicket(Request $request)
    {
        $requestAllRequest = $request->all();
        $requestAllData    = $request->getContent();

        //如果$requestAllData不为空，将xml数据转为数组
        $xml_array = $this->FromXml($requestAllData);
        if(isset($xml_array['appid'])){
            if(!empty($xml_array['appid']) && $xml_array['status'] == 0){
                if(!empty($xml_array['auth_code'])){
                    //说明是创建小程序成功之后的事件通知
                    DB::table($this->customerAppletsRegisterWeApps)->insert([
                        't_appid'               => $xml_array['AppId'],
                        'CreateTime'            => isset($xml_array['CreateTime']) ? $xml_array['CreateTime'] : '',
                        'appid'                 => isset($xml_array['appid']) ? $xml_array['appid'] : '',
                        'status'                => isset($xml_array['status']) ? $xml_array['status'] : '',
                        'auth_code'             => isset($xml_array['auth_code']) ? $xml_array['auth_code'] : '',
                        'name'                  => isset($xml_array['info']['name']) ? $xml_array['info']['name'] : '',
                        'code'                  => isset($xml_array['info']['code']) ? $xml_array['info']['code'] : '',
                        'code_type'             => isset($xml_array['info']['code_type']) ? $xml_array['info']['code_type'] : '',
                        'legal_persona_wechat'  => isset($xml_array['info']['legal_persona_wechat']) ? $xml_array['info']['legal_persona_wechat'] : '',
                        'legal_persona_name'    => isset($xml_array['info']['legal_persona_name']) ? $xml_array['info']['legal_persona_name'] : '',
                        'component_phone'       => isset($xml_array['info']['component_phone']) ? $xml_array['info']['component_phone'] : '',
                    ]);
                }
            }
        }

        $config = [
            'app_id'   => $this->app_id,
            'secret'   => $this->secret,
            'token'    => $this->token,
            'aes_key'  => $this->aes_key
        ];

        $openPlatform = Factory::openPlatform($config);

        $server       = $openPlatform->server;

        // 处理授权成功事件
        $server->push(function ($message) use ($config) {
//            Log::info("授权成功事件：");
//            Log::info(json_encode($message));

            //说明是创建小程序成功之后的事件通知
            $authorizeAppidInfo = DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $message['AppId'],'AuthorizerAppid' => $message['AuthorizerAppid']])->first();
            if(empty($authorizeAppidInfo)){
                DB::table($this->customerAppletsAuthorizeAppid)->insert([
                    't_appid'                   => $message['AppId'],
                    'CreateTime'                => isset($message['CreateTime']) ? $message['CreateTime'] : '',
                    'InfoType'                  => isset($message['InfoType']) ? $message['InfoType'] : '',
                    'AuthorizerAppid'           => isset($message['AuthorizerAppid']) ? $message['AuthorizerAppid'] : '',
                    'AuthorizationCode'         => isset($message['AuthorizationCode']) ? $message['AuthorizationCode'] : '',
                    'AuthorizationCodeExpiredTime'  => isset($message['AuthorizationCodeExpiredTime']) ? $message['AuthorizationCodeExpiredTime'] : '',
                    'PreAuthCode'                   => isset($message['PreAuthCode']) ? $message['PreAuthCode'] : '',
                    'created_at' => date("Y-m-d H:i:s",time()),
                    'updated_at' => date("Y-m-d H:i:s",time())
                ]);
            }else{
                DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $message['AppId'],'AuthorizerAppid' => $message['AuthorizerAppid']])->update([
                    'CreateTime'                => isset($message['CreateTime']) ? $message['CreateTime'] : '',
                    'InfoType'                  => isset($message['InfoType']) ? $message['InfoType'] : '',
                    'AuthorizationCode'         => isset($message['AuthorizationCode']) ? $message['AuthorizationCode'] : '',
                    'AuthorizationCodeExpiredTime'  => isset($message['AuthorizationCodeExpiredTime']) ? $message['AuthorizationCodeExpiredTime'] : '',
                    'PreAuthCode'                   => isset($message['PreAuthCode']) ? $message['PreAuthCode'] : '',
                    'updated_at' => date("Y-m-d H:i:s",time())
                ]);
            }

            //使用授权码获取授权信息
            $authorizationCodeResult = $this->getAuthorizerAccessToken($config['app_id'],$message['AuthorizationCode']);
            if($authorizationCodeResult['status'] == 200){
                $authorizer_access_token = $authorizationCodeResult['data']['authorization_info']['authorizer_access_token'];

                //更新该授权方 appid的authorizer_refresh_token
                DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $message['AppId'],'AuthorizerAppid' => $message['AuthorizerAppid']])->update([
                    'authorizer_refresh_token' =>$authorizationCodeResult['data']['authorization_info']['authorizer_refresh_token'],
                    'updated_at' => date("Y-m-d H:i:s",time())
                ]);

                //设置服务器域名
                $settingServerDomain = [
                    "action"            => "add",
                    "requestdomain"     => [$this->domain],
                    "wsrequestdomain"   => [],
                    "uploaddomain"      => [$this->domain],
                    "downloaddomain"    => [$this->domain]
                ];
                $requestDomainUrl = "https://api.weixin.qq.com/wxa/modify_domain?access_token=".$authorizer_access_token;
                $requestDomainResult = $this->curl_post_https($requestDomainUrl,json_encode($settingServerDomain,JSON_UNESCAPED_UNICODE));
                $requestDomainResult = json_decode($requestDomainResult,true);
                if($requestDomainResult['errcode'] == 0){
                    Log::info("设置服务器域名成功:".json_encode($requestDomainResult));
                }else{
                    Log::info("设置服务器域名失败:".json_encode($requestDomainResult));
                }

                //第一步：添加插件
                $pluginRequestData = [
                    'action'       => 'apply',
                    'plugin_appid' => "wxf3f436ba9bd4be7b",
                    'user_version' => '1.1.5'
                ];

                $pluginRequestUrl = "https://api.weixin.qq.com/wxa/plugin?access_token=".$authorizer_access_token;

                $pluginResult = $this->curl_post_https($pluginRequestUrl,json_encode($pluginRequestData,JSON_UNESCAPED_UNICODE));

                $pluginResult = json_decode($pluginResult,true);

                if($pluginResult['errcode'] == 0 || $pluginResult['errcode'] == 89237){
                    //说明添加微信支付券的插件成功
                    //Log::info("添加微信支付券成功：".json_encode($pluginResult));
                }else{
                    Log::info("添加微信支付券失败：".json_encode($pluginResult));
                }
            }
        }, Guard::EVENT_AUTHORIZED);

        // 处理授权更新事件
        $server->push(function ($message) {
            Log::info("授权更新事件：");
            Log::info(json_encode($message));
        }, Guard::EVENT_UPDATE_AUTHORIZED);

        // 处理授权取消事件
        $server->push(function ($message) {
            Log::info("授权取消事件：");
            Log::info(json_encode($message));
            $authorizeAppidInfo = DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $message['AppId'],'AuthorizerAppid' => $message['AuthorizerAppid']])->first();
            if(!empty($authorizeAppidInfo)){
                DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $message['AppId'],'AuthorizerAppid' => $message['AuthorizerAppid']])->delete();
            }
        }, Guard::EVENT_UNAUTHORIZED);

        // VerifyTicket事件
        $server->push(function ($message) use ($config) {
            $getComponentAccessTokenData  = [
                //第三方平台appid
                'component_appid'         => $config['app_id'],
                //第三方平台appsecret
                'component_appsecret'     => $config['secret'],
                //微信后台推送的ticket
                'component_verify_ticket' => $message['ComponentVerifyTicket'],
            ];

            $component_access_token_res = $this->getComponentAccessToken($getComponentAccessTokenData);
            $component_access_token_res = json_decode($component_access_token_res,true);
            if(!empty($component_access_token_res['component_access_token']) && isset($component_access_token_res['component_access_token'])){
                Cache::put('component_access_token', $component_access_token_res['component_access_token'], 110);
            }
        }, Guard::EVENT_COMPONENT_VERIFY_TICKET);
        return $server->serve();
    }

    /**
     * 快速创建小程序，通过该接口创建小程序默认为“已认证”。为降低接入小程序的成本门槛，通过该接口创建的小程序无需交 300 元认证费
     * @param Request $request
     * @return false|string
     */
    public function fastRegisterWeApp(Request $request)
    {
        $store_id = $request->post('store_id', ''); //门店id
        //企业名（需与工商部门登记信息一致）
        $name                 = $request->post('name', '');
        //企业代码
        $code                 = $request->post('code', '');
        //企业代码类型 1：统一社会信用代码（18 位） 2：组织机构代码（9 位 xxxxxxxx-x） 3：营业执照注册号(15 位)
        $code_type            = $request->post('code_type', 1);
        //法人微信号
        $legal_persona_wechat = $request->post('legal_persona_wechat', '');
        //法人姓名（绑定银行卡）
        $legal_persona_name   = $request->post('legal_persona_name', '');
        //第三方联系电话
        $component_phone      = $request->post('component_phone', '');
        //第三方平台接口的调用凭据。令牌的获取是有限制的，每个令牌的有效期为 2 小时
        $component_access_token = Cache::get("component_access_token");

        if (!isset($store_id) || empty($store_id)) {
            return $this->responseDataJson(202, '门店id不能为空');
        }
        if(empty($component_access_token)){
            return $this->responseDataJson(202,'component_access_token数据为空,请稍等10分钟再进行尝试');
        }
        try {
            $storeObj = Store::where('store_id', $store_id)
                ->where('is_close', 0)
                ->where('is_delete', 0)
                ->first();
            if (!$storeObj) {
                return $this->responseDataJson(202, '门店不存在或状态异常');
            }

            $componentTokenData = [
                'name'                  => $name,
                'code'                  => $code,
                'code_type'             => $code_type,
                'legal_persona_wechat'  => $legal_persona_wechat,
                'legal_persona_name'    => $legal_persona_name,
                'component_phone'       => $component_phone,
            ];

            //信息入库
            $customerappletsStoresObj = CustomerAppletsStore::where('store_id', $store_id)
                ->where('type', 1)
                ->first();
            if ($customerappletsStoresObj) {
                $updateRes = $customerappletsStoresObj->update($componentTokenData);
                if (!$updateRes) {
                    Log::info('微信小程序-快速创建小程序-信息入库-更新失败');
                    Log::info($store_id);
                }
            } else {
                $addRes = CustomerAppletsStore::create([
                    'store_id'              => $store_id,
                    'name'                  => $name,
                    'code'                  => $code,
                    'code_type'             => $code_type,
                    'legal_persona_wechat'  => $legal_persona_wechat,
                    'legal_persona_name'    => $legal_persona_name,
                    'component_phone'       => $component_phone,
                ]);
                if (!$addRes) {
                    Log::info('微信小程序-快速创建小程序-信息入库-新建失败');
                    Log::info($store_id);
                }
            }

            $url = 'https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=create&component_access_token='.$component_access_token;

            $result = $this->curl_post_https($url,json_encode($componentTokenData,JSON_UNESCAPED_UNICODE));

            $result = json_decode($result,true);

            if($result['errcode'] == 0){
                return $this->responseDataJson(200,$result['errmsg']);
            }else{
                $errmsg = $this->getCodeMessage($result['errcode']);
                return $this->responseDataJson($result['errcode'],$errmsg ? $errmsg : $result['errcode'].":".$result['errmsg']);
            }
        } catch (\Exception $e) {
            return $this->responseDataJson(202,$e->getMessage().' | '.$e->getFile().' | '.$e->getLine(),"");
        }
    }

    /**
     * 查询创建任务状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function fastRegisterWeAppStatus(Request $request){
        $name                 = $request->post('name', ''); //企业名（需与工商部门登记信息一致）
        $legal_persona_wechat = $request->post('legal_persona_wechat', ''); //法人微信号
        $legal_persona_name   = $request->post('legal_persona_name', ''); //法人姓名（绑定银行卡）

        $component_access_token = Cache::get("component_access_token"); //第三方平台接口的调用凭据。令牌的获取是有限制的，每个令牌的有效期为 2 小时
        if(empty($component_access_token)){
            return $this->responseDataJson(202,'component_access_token数据为空,请稍等10分钟再进行尝试');
        }

        try {
            $componentTokenData = [
                'name'                 => $name,
                'legal_persona_wechat' => $legal_persona_wechat,
                'legal_persona_name'   => $legal_persona_name
            ];
            $url = 'https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=search&component_access_token='.$component_access_token;

            $result = $this->curl_post_https($url,json_encode($componentTokenData,JSON_UNESCAPED_UNICODE));

            $result = json_decode($result,true);

            if($result['errcode'] == 0){
                return $this->responseDataJson(200,$result['errmsg']);
            }else{
                $errmsg = $this->getCodeMessage($result['errcode']);
                return $this->responseDataJson($result['errcode'],$errmsg ? $errmsg : $result['errcode'].":".$result['errmsg']);
            }
        } catch (\Exception $e) {
            return $this->responseDataJson(202,$e->getMessage().' | '.$e->getFile().' | '.$e->getLine(),"");
        }
    }

    /**
     * 拿到商家认证之后的appid
     * 下一步：进行授权
     * 首先：  获取预授权码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPreAuthCode(Request $request){
        $requestAllData  = $request->all();
        $component_appid = isset($requestAllData['component_appid']) ? (!empty($requestAllData['component_appid']) ? $requestAllData['component_appid'] : $this->app_id) : $this->app_id;

        if(Cache::has("pre_auth_code")){
            $pre_auth_code = Cache::get("pre_auth_code");
            if(!empty($pre_auth_code)){
                return $this->responseDataJson(200,"获取成功",['pre_auth_code' => $pre_auth_code]);
            }
        }

        $component_access_token = Cache::get("component_access_token"); //第三方平台接口的调用凭据。令牌的获取是有限制的，每个令牌的有效期为 2 小时

        if(empty($component_access_token)){
            return $this->responseDataJson(202,'component_access_token数据为空,请稍等10分钟再进行尝试');
        }

        try {
            $componentTokenData = [
                'component_appid' => $component_appid,
            ];

            $url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token='.$component_access_token;

            $result = $this->curl_post_https($url,json_encode($componentTokenData));

            $result = json_decode($result,true);
            // 点击小程序授权按钮现在不方便测，等能测的时候在打开
            // $request['app_id'] = $this->app_id;

            if(!empty($result['pre_auth_code']) && isset($result['pre_auth_code'])){
                Cache::put('pre_auth_code', $result['pre_auth_code'], ($result['expires_in']/60 - 10));
                return $this->responseDataJson(200,"获取成功",$result);
            }else{
                $errmsg = $this->getCodeMessage($result['errcode']);
                return $this->responseDataJson($result['errcode'],$errmsg ? $errmsg : $result['errcode'].":".$result['errmsg']);
            }
        } catch (\Exception $e) {
            return $this->responseDataJson(202,$e->getMessage().' | '.$e->getFile().' | '.$e->getLine(),"");
        }
    }

    /**
     * 使用授权码获取授权信息
     * @param $component_appid
     * @param $authorization_code
     * @return array
     */
    public function getAuthorizerAccessToken($component_appid,$authorization_code){

        $component_access_token = Cache::get("component_access_token"); //第三方平台接口的调用凭据。令牌的获取是有限制的，每个令牌的有效期为 2 小时

        if(empty($component_access_token)){
            return ['status' => 202,'message' => 'component_access_token数据为空,请稍等10分钟再进行尝试'];
        }

        try {
            $componentTokenData = [
                'component_appid'    => $component_appid,
                'authorization_code' => $authorization_code
            ];

            $url    = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token='.$component_access_token;

            $result = $this->curl_post_https($url,json_encode($componentTokenData));

            $result = json_decode($result,true);

            if(!empty($result['authorization_info']) && isset($result['authorization_info'])){
                //一旦丢失，只能让用户重新授权，才能再次拿到新的刷新令牌
//                Cache::put('authorizer_refresh_token', $result['authorization_info']['authorizer_refresh_token'], 3600 * 24 * 30);
                return ['status' => 200,'message' => '获取成功','data' => $result];
            }else{
                $errmsg = $this->getCodeMessage($result['errcode']);
                return ['status' => $result['errcode'],'message' => $errmsg ? $errmsg : $result['errcode'].":".$result['errmsg']];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage().' | '.$e->getFile().' | '.$e->getLine()];
        }
    }

    /**
     * 获取/刷新接口调用令牌
     * @param $component_appid
     * @param $authorizer_appid
     * @return array
     */
    public function getAuthorizerToken($component_appid,$authorizer_appid,$authorizer_refresh_token){

        $component_access_token = Cache::get("component_access_token"); //第三方平台接口的调用凭据。令牌的获取是有限制的，每个令牌的有效期为 2 小时

        if(empty($component_access_token)){
            return ['status' => 202,'message' => 'component_access_token数据为空,请稍等10分钟再进行尝试'];
        }

        try {

            //如果缓存中有数据，直接读取缓存中的数据
            $authorizer_access_token = Cache::get($authorizer_appid."_authorizer_access_token");

            if($authorizer_access_token){
                return ['status' => 200,'message' => '获取成功','data' => ['authorizer_access_token' => $authorizer_access_token]];
            }
            //否则，再去请求接口
            $componentTokenData = [
                'component_appid'    => $component_appid,
                'authorizer_appid'   => $authorizer_appid,
                'authorizer_refresh_token' => $authorizer_refresh_token
            ];

            $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$component_access_token;

            $result = $this->curl_post_https($url,json_encode($componentTokenData));

            $result = json_decode($result,true);

            if(!empty($result['authorizer_access_token']) && isset($result['authorizer_access_token'])){
                //一旦丢失，只能让用户重新授权，才能再次拿到新的刷新令牌
                Cache::put($authorizer_appid.'_authorizer_access_token', $result['authorizer_access_token'], 120);

                //更新该授权方 appid的authorizer_refresh_token
                DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $component_appid,'AuthorizerAppid' => $authorizer_appid])->update([
                    'authorizer_refresh_token' => $result['authorizer_refresh_token'],
                    'updated_at'               => date("Y-m-d H:i:s",time())
                ]);

                return ['status' => 200,'message' => '获取成功','data' => $result];
            }else{
                $errmsg = $this->getCodeMessage($result['errcode']);
                return ['status' => $result['errcode'],'message' => $errmsg ? $errmsg : $result['errcode'].":".$result['errmsg']];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage().' | '.$e->getFile().' | '.$e->getLine()];
        }
    }

    /**
     * 获取基本信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAccountBasicInfo($authorizer_access_token){
        //获取小程序基本信息
        $url = 'https://api.weixin.qq.com/cgi-bin/account/getaccountbasicinfo?access_token='.$authorizer_access_token;
        $getCateGoryResult = $this->curl_get_https($url);
        $getCateGoryResult = json_decode($getCateGoryResult,true);
        if($getCateGoryResult['errcode'] == 0){

            return "";
        }else{
            $errmsg = $this->getCodeMessage($getCateGoryResult['errcode']);
            return "";
        }
    }

    /**
     * 拉取所有已授权的帐号信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAuthorizerList(Request $request){
        $requestAllData  = $request->all();
        $component_appid = isset($requestAllData['component_appid']) ? (!empty($requestAllData['component_appid']) ? $requestAllData['component_appid'] : $this->app_id) : $this->app_id;
        //第三方平台接口的调用凭据。令牌的获取是有限制的，每个令牌的有效期为 2 小时
        $component_access_token = Cache::get("component_access_token");

        if(empty($component_access_token)){
            return $this->responseDataJson(202,'component_access_token数据为空,请稍等10分钟再进行尝试');
        }

        $page = $requestAllData['page'];
        $count = isset($requestAllData['count']) ? $requestAllData['count'] : 10;
        $offset = ($page - 1) * $count;

        try {
            $componentTokenData = [
                'component_appid' => $component_appid,
                'offset'          => $offset,
                'count'           => $count
            ];

            $url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_list?component_access_token='.$component_access_token;

            $result = $this->curl_post_https($url,json_encode($componentTokenData));

            $result = json_decode($result,true);

            if(!empty($result['total_count']) && isset($result['total_count'])){

                //获取授权方的帐号基本信息
                if($result['total_count'] > 0){
                    $applets = $result['list'];

                    $newAppletsArray = [];
                    foreach ($applets as $key => $val){
                        array_push($newAppletsArray,$val);
                    }

                    foreach ($newAppletsArray as $key => $val){
                        $componentRequestInfo = [
                            'component_appid'  => $this->app_id,
                            'authorizer_appid' => $val['authorizer_appid']
                        ];

                        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token='.$component_access_token;

                        $authorizerResult = $this->curl_post_https($url,json_encode($componentRequestInfo));

                        $authorizerResult = json_decode($authorizerResult,true);

                        if(isset($authorizerResult['authorizer_info']) && !empty($authorizerResult['authorizer_info'])){
                            $newAppletsArray[$key]['authorizer_appid_name'] = $authorizerResult['authorizer_info']['nick_name'];
                        }else{
                            $newAppletsArray[$key]['authorizer_appid_name'] = "";
                        }

                        //查询最新一次提交的审核状态
                        if(!empty($val['refresh_token'])){
                            $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$val['authorizer_appid'],$val['refresh_token']);
                            if($authorizerTokenResult['status'] == 200){
                                $authorizerToken = $authorizerTokenResult['data']['authorizer_access_token'];

                                $url = 'https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token='.$authorizerToken;

                                $getLatestGuditStatus = $this->curl_get_https($url);

                                $getLatestGuditStatus = json_decode($getLatestGuditStatus,true);

                                if($getLatestGuditStatus['errcode'] == 0){
                                    $newAppletsArray[$key]['authorizer_appid_status'] = $getLatestGuditStatus['status'];
                                    switch ($getLatestGuditStatus['status']){
                                        case 0:
                                            $newAppletsArray[$key]['authorizer_appid_status_desc'] = "审核成功";
                                            break;
                                        case 1:
                                            $newAppletsArray[$key]['authorizer_appid_status_desc'] = "审核被拒绝";
                                            $newAppletsArray[$key]['authorizer_appid_status_reason'] = $getLatestGuditStatus['reason'];
                                            break;
                                        case 2:
                                            $newAppletsArray[$key]['authorizer_appid_status_desc'] = "审核中";
                                            break;
                                        case 3:
                                            $newAppletsArray[$key]['authorizer_appid_status_desc'] = "已撤回";
                                            break;
                                        default:
                                            $newAppletsArray[$key]['authorizer_appid_status_desc'] = "未发布审核";
                                    }
                                }
                            }
                        }
                    }
                    if(!empty($newAppletsArray)){
                        $result['list'] = $newAppletsArray;
                    }
                }
                return response()->json([
                    'status'  => 200,
                    'message' => "获取成功",
                    'data'    => isset($result['list']) ? $result['list'] : [],
                    'total_count' => $result['total_count'],
                    'page'  => (int)$requestAllData['page'],
                    't' => (int)$requestAllData['count'],
                ]);
            }else{
                $errmsg = $this->getCodeMessage($result['errcode']);
                return $this->responseDataJson($result['errcode'],$errmsg ? $errmsg : $result['errcode'].":".$result['errmsg']);
            }
        } catch (\Exception $e) {
            return $this->responseDataJson(202,$e->getMessage().' | '.$e->getFile().' | '.$e->getLine(),"");
        }
    }

    /**
     * 上传代码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadCode(Request $request){

        $requestAllData = $request->all();

        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(202,"门店id不可为空");
        }
        if(!isset($requestAllData['store_applets_desc']) || empty($requestAllData['store_applets_desc'])){
            return $this->responseDataJson(202,"小程序描述内容不可为空");
        }
        if(!isset($requestAllData['template_id']) || empty($requestAllData['template_id'])){
            return $this->responseDataJson(202,"小程序模板id不可为空");
        }
        if(!isset($requestAllData['user_version']) || empty($requestAllData['user_version'])){
            return $this->responseDataJson(202,"微信小程序版本不可为空");
        }

        $storeObj = Store::where('store_id', $requestAllData['store_id'])
            ->where('is_close', 0)
            ->where('is_delete', 0)
            ->first();
        if (!$storeObj) {
            return $this->responseDataJson(202, "门店不存在或状态异常");
        }

        //信息入库
        $customerAppletsStoreObj = CustomerAppletsStore::where('store_id', $requestAllData['store_id'])
            ->where('type', 1)
            ->first();
        $customerAppletsStoreUpdateData = [
            'store_applets_desc' => $requestAllData['store_applets_desc'],
            'template_id' => $requestAllData['template_id'],
            'user_version' => $requestAllData['user_version'],
        ];
        if ($customerAppletsStoreObj) {
            $updateRes = $customerAppletsStoreObj->update($customerAppletsStoreUpdateData);
            if (!$updateRes) {
                Log::info('微信小程序-上传代码-信息入库-更新失败');
                Log::info($requestAllData['store_id']);
                Log::info($requestAllData['template_id']);
                Log::info($requestAllData['user_version']);
            }
        } else {
            $addRes = CustomerAppletsStore::create([
                'type' => 1,
                'store_id' => $requestAllData['store_id'],
                'store_applets_desc' => $requestAllData['store_applets_desc'],
                'template_id' => $requestAllData['template_id'],
                'user_version' => $requestAllData['user_version'],
            ]);
            if (!$addRes) {
                Log::info('微信小程序-上传代码-信息入库-新建失败');
                Log::info($requestAllData['store_id']);
                Log::info($requestAllData['template_id']);
                Log::info($requestAllData['user_version']);
            }
        }

        //第三方平台appid
        $component_appid = $this->app_id;

        $storeConfigAppletsInfo = DB::table("merchant_store_appid_secrets")->where(['store_id' => $requestAllData['store_id']])->first();
        if(empty($storeConfigAppletsInfo) || !$storeConfigAppletsInfo){
            return $this->responseDataJson(202,"请先完善小程序信息");
        }

        // if(empty($storeConfigAppletsInfo->wechat_appid) || empty($storeConfigAppletsInfo->wechat_secret)){
        //     return $this->responseDataJson(202,"请先完善小程序appid和secret密钥信息");
        // }
        if(empty($storeConfigAppletsInfo->wechat_appid)){
            return $this->responseDataJson(202,"请先完善小程序appid信息");
        }

        $customerAppletsAuthorizeAppid = DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $component_appid,'AuthorizerAppid' => $storeConfigAppletsInfo->wechat_appid])->first();

        if(empty($customerAppletsAuthorizeAppid) || !$customerAppletsAuthorizeAppid){
            return $this->responseDataJson(202,"该小程序未授权成功，不可上传代码");
        }

        if(empty($customerAppletsAuthorizeAppid->authorizer_refresh_token)){
            return $this->responseDataJson(202,"该小程序授权时，authorizer_refresh_token刷新令牌为空");
        }

        $authorizerTokenResult = $this->getAuthorizerToken($component_appid,$storeConfigAppletsInfo->wechat_appid,$customerAppletsAuthorizeAppid->authorizer_refresh_token);
        if($authorizerTokenResult['status'] == 200) {
            $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];
            //再次更新刷新令牌
            if(isset($authorizerTokenResult['data']['authorizer_refresh_token']) && !empty($authorizerTokenResult['data']['authorizer_refresh_token'])){
                //更新该授权方 appid的authorizer_refresh_token
                $updateRefreshToken = DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $component_appid,'AuthorizerAppid' => $storeConfigAppletsInfo->wechat_appid])->update([
                    'authorizer_refresh_token' =>$authorizerTokenResult['data']['authorizer_refresh_token'],
                    'updated_at' => date("Y-m-d H:i:s",time())
                ]);
                if(!$updateRefreshToken){
                    return $this->responseDataJson(202,"更新authorizer_refresh_token刷新令牌失败");
                }
            }

            if(isset($requestAllData['nick_name']) && !empty($requestAllData['nick_name'])){

                if(!isset($requestAllData['license']) || empty($requestAllData['license'])){
                    return $this->responseDataJson(202,"门店经营执照不可为空");
                }

                //信息入库
                if ($customerAppletsStoreObj) {
                    $updateRes2 = $customerAppletsStoreObj->update([
                        'nick_name' => $requestAllData['nick_name'],
                        'license' => $requestAllData['license']
                    ]);
                    if (!$updateRes2) {
                        Log::info('微信小程序-上传代码-信息入库-更新2失败');
                        Log::info($requestAllData['store_id']);
                        Log::info($requestAllData['nick_name']);
                        Log::info($requestAllData['license']);
                    }
                }

                //微信认证名称检测
                $checkwxverifynickname = [
                    'nick_name'  => $requestAllData['nick_name'],
                ];

                $checkwxverifynicknameUrl    = 'https://api.weixin.qq.com/cgi-bin/wxverify/checkwxverifynickname?access_token='.$authorizer_access_token;

                $checkwxverifynicknameResult = $this->curl_post_https($checkwxverifynicknameUrl,json_encode($checkwxverifynickname,JSON_UNESCAPED_UNICODE));

                $checkwxverifynicknameResult = json_decode($checkwxverifynicknameResult,true);
                if($checkwxverifynicknameResult['errcode'] != 0){
                    $errmsg = $this->getCodeMessage($checkwxverifynicknameResult['errcode']);
                    return $this->responseDataJson($checkwxverifynicknameResult['errcode'],$errmsg ? $errmsg : "微信认证名称检测:".$checkwxverifynicknameResult['errcode']."/".$checkwxverifynicknameResult['errmsg']);
                }

                //认证名称通过，进行设置名称
                $setnickname = [
                    'nick_name'  => $requestAllData['nick_name'],
                    'license'    => $requestAllData['license'],
                ];
                $setnicknameUrl    = 'https://api.weixin.qq.com/wxa/setnickname?access_token='.$authorizer_access_token;

                $setnicknameResult = $this->curl_post_https($setnicknameUrl,json_encode($setnickname,JSON_UNESCAPED_UNICODE));

                $setnicknameResult = json_decode($setnicknameResult,true);

                if($setnicknameResult['errcode'] == 0){
                    $authorizerAppidInfo = DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $this->app_id,'AuthorizerAppid' => $requestAllData['authorizer_appid']])->first();
                    if(!empty($authorizerAppidInfo)){
                        $updateAuthorizerAppid = [];
                        if(empty($setnicknameResult['audit_id']) || !isset($setnicknameResult['audit_id'])){
                            //若接口未返回 audit_id，说明名称已直接设置成功，无需审核；
                        }else{
                            $updateAuthorizerAppid['applet_name_audit_status'] = 1;
                            $updateAuthorizerAppid['applet_name_audit_id'] = $setnicknameResult['audit_id'];
                        }
                        $updateAuthorizerAppid['applet_name'] = $requestAllData['nick_name'];
                        $updateAuthorizerAppid['updated_at']  = date("Y-m-d H:i:s",time());
                        $updateAuthorizerAppidResult = DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $this->app_id,'AuthorizerAppid' => $requestAllData['authorizer_appid']])->update($updateAuthorizerAppid);
                        if(!$updateAuthorizerAppidResult){
                            return $this->responseDataJson(202,"更新小程序数据库名称信息失败");
                        }
                    }
                }else{
                    $errmsg = $this->getCodeMessage($setnicknameResult['errcode']);
                    return $this->responseDataJson(202,$errmsg ? $errmsg : $setnicknameResult['errcode'].":".$setnicknameResult['errmsg']);
                }
            }

            Log::info("开始发布代码");
            //授权成功，发布代码
            try {
                $commitAppletsData = [
                    'template_id'  => $requestAllData['template_id'],
                    'ext_json'     => "{\"extAppid\":\"{$component_appid}\",\"ext\":{\"name\":\"\",\"store_id\":\"{$requestAllData['store_id']}\"},\"extPages\":{},\"pages\":[\"pages/index/index\",\"pages/commodity/commodity\",\"pages/createAddress/createAddress\",\"pages/payment/payment\",\"pages/paymentResults/paymentResults\",\"pages/refund/refund\",\"pages/storeDetail/storeDetail\",\"pages/storeQuali/storeQuali\",\"pages/user/user\",\"pages/userAddress/userAddress\",\"pages/userCart/userCart\",\"pages/userCoupon/userCoupon\",\"pages/userOrder/userOrder\",\"pages/userOrderDetails/userOrderDetails\",\"pages/vipRecharge/vipRecharge\",\"pages/ordermenu/ordermenu\",\"pages/goPay/goPay\",\"pages/goPaysuccess/goPaysuccess\"],\"window\":{},\"networkTimeout\":{},\"tabBar\":{},\"plugin\":{}}",
                    'user_version' => $requestAllData['user_version'],
                    'user_desc'    => "上传代码",
                ];

                $url    = 'https://api.weixin.qq.com/wxa/commit?access_token='.$authorizer_access_token;

                $result = $this->curl_post_https($url,json_encode($commitAppletsData,JSON_UNESCAPED_UNICODE));

                $result = json_decode($result,true);

                if($result['errcode'] == 0){
                    Log::info("上传发布代码成功：".json_encode($result));

                    //小程序提交审核
                    Log::info("开始提交审核");

                    $submitAuditRequestData = [
                        "version_desc" => $requestAllData['store_applets_desc'],
                    ];

                    $submitAuditRequestUrl  = "https://api.weixin.qq.com/wxa/submit_audit?access_token=".$authorizer_access_token;

                    $submitAuditResult      = $this->curl_post_https($submitAuditRequestUrl,json_encode($submitAuditRequestData,JSON_UNESCAPED_UNICODE));

                    $submitAuditResult = json_decode($submitAuditResult,true);

                    if($submitAuditResult['errcode'] == 0){
                        return $this->responseDataJson(200,"提交审核成功，请等待微信官方通知");
                    }else{
                        $errmsg = $this->getCodeMessage($submitAuditResult['errcode']);
                        return $this->responseDataJson($submitAuditResult['errcode'],$errmsg ? $errmsg : "提交审核失败:".$submitAuditResult['errcode'].":".$submitAuditResult['errmsg']);
                    }
                }else{
                    $errmsg = $this->getCodeMessage($result['errcode']);
                    return $this->responseDataJson($result['errcode'],$errmsg ? $errmsg : "上传发布代码失败:".$result['errcode']."：".$result['errmsg']);
                }
            } catch (\Exception $e) {
                return $this->responseDataJson(202,"授权成功，发布代码程序运行出错:".$e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
            }
        }else{
            return $this->responseDataJson($authorizerTokenResult['status'],$authorizerTokenResult['message']);
        }
    }

    /**
     * 微信认证名称检测,并且修改名称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkWxVerifyNickname(Request $request){

        $requestAllData  = $request->all();

        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }
        if(!isset($requestAllData['nick_name']) || empty($requestAllData['nick_name'])){
            return $this->responseDataJson(202,"微信小程序名称不可为空");
        }
        if(!isset($requestAllData['license']) || empty($requestAllData['license'])){
            return $this->responseDataJson(202,"门店经营执照不可为空");
        }

        $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$requestAllData['authorizer_appid'],$requestAllData['refresh_token']);
        if($authorizerTokenResult['status'] == 200){
            $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];

            $authorizerAppidInfo = DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $this->app_id,'AuthorizerAppid' => $requestAllData['authorizer_appid']])->first();
            if(!empty($authorizerAppidInfo)){
                //说明最近更改过名称
                if(!empty($authorizerAppidInfo->applet_name_audit_id)){
                    //查询改名审核状态
                    $appletNameAuditStatus = [
                        'audit_id' => $authorizerAppidInfo->applet_name_audit_id
                    ];
                    $appletNameAuditStatusUrl = "https://api.weixin.qq.com/wxa/api_wxa_querynickname?access_token=".$authorizer_access_token;
                    $appletNameAuditStatusResult = $this->curl_post_https($appletNameAuditStatusUrl,json_encode($appletNameAuditStatus,JSON_UNESCAPED_UNICODE));
                    $appletNameAuditStatusResult = json_decode($appletNameAuditStatusResult,true);
                    if($appletNameAuditStatusResult['errcode'] == 0){
                        if($appletNameAuditStatusResult['audit_stat'] == 1){
                            return $this->responseDataJson(202,"当前名称还在审核中,暂时不可再次提交修改");
                        }
                    }
                }
            }

            //微信认证名称检测
            $checkwxverifynickname = [
                'nick_name'  => $requestAllData['nick_name'],
            ];

            $checkwxverifynicknameUrl    = 'https://api.weixin.qq.com/cgi-bin/wxverify/checkwxverifynickname?access_token='.$authorizer_access_token;

            $checkwxverifynicknameResult = $this->curl_post_https($checkwxverifynicknameUrl,json_encode($checkwxverifynickname,JSON_UNESCAPED_UNICODE));

            $checkwxverifynicknameResult = json_decode($checkwxverifynicknameResult,true);
            if($checkwxverifynicknameResult['errcode'] != 0){
                $errmsg = $this->getCodeMessage($checkwxverifynicknameResult['errcode']);
                return $this->responseDataJson($checkwxverifynicknameResult['errcode'],$errmsg ? $errmsg : "微信认证名称检测:".$checkwxverifynicknameResult['errcode'].":".$checkwxverifynicknameResult['errmsg']);
            }

            //认证名称通过，进行设置名称
            $setnickname = [
                'nick_name'  => $requestAllData['nick_name'],
                'license'    => $requestAllData['license'],
            ];
            $setnicknameUrl    = 'https://api.weixin.qq.com/wxa/setnickname?access_token='.$authorizer_access_token;

            $setnicknameResult = $this->curl_post_https($setnicknameUrl,json_encode($setnickname,JSON_UNESCAPED_UNICODE));

            $setnicknameResult = json_decode($setnicknameResult,true);

            if($setnicknameResult['errcode'] == 0){
                if(!empty($authorizerAppidInfo)){
                    $updateAuthorizerAppid = [];
                    if(empty($setnicknameResult['audit_id']) || !isset($setnicknameResult['audit_id'])){
                        //若接口未返回 audit_id，说明名称已直接设置成功，无需审核；
                    }else{
                        $updateAuthorizerAppid['applet_name_audit_status'] = 1;
                        $updateAuthorizerAppid['applet_name_audit_id'] = $setnicknameResult['audit_id'];
                    }
                    $updateAuthorizerAppid['applet_name'] = $requestAllData['nick_name'];
                    $updateAuthorizerAppid['updated_at']  = date("Y-m-d H:i:s",time());
                    $updateAuthorizerAppidResult = DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $this->app_id,'AuthorizerAppid' => $requestAllData['authorizer_appid']])->update($updateAuthorizerAppid);
                    if(!$updateAuthorizerAppidResult){
                        return $this->responseDataJson(202,"更新小程序数据库名称信息失败");
                    }
                }
                return $this->responseDataJson(200,"设置成功，请等待微信官方通知");
            }else{
                $errmsg = $this->getCodeMessage($setnicknameResult['errcode']);
                return $this->responseDataJson(202,$errmsg ? $errmsg : $setnicknameResult['errcode'].":".$setnicknameResult['errmsg']);
            }
        }else{
            return $this->responseDataJson(202,$authorizerTokenResult['message']);
        }
    }

    /**
     * 修改头像
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function modifyHeadImage(Request $request){
        $requestAllData  = $request->all();

        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }
        if(!isset($requestAllData['head_img_media_id']) || empty($requestAllData['head_img_media_id'])){
            return $this->responseDataJson(202,"头像不可为空");
        }

        if(!isset($requestAllData['path']) || empty($requestAllData['path'])){
            return $this->responseDataJson(202,"头像path不可为空");
        }

        $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$requestAllData['authorizer_appid'],$requestAllData['refresh_token']);
        if($authorizerTokenResult['status'] == 200){
            $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];
            //修改头像
            $modifyHeadImage = [
                'head_img_media_id'  => $requestAllData['head_img_media_id'],
                'x1' => "0",
                'y1' => "0",
                'x2' => "0",
                'y2' => "0"
            ];

            $modifyHeadImageUrl    = 'https://api.weixin.qq.com/cgi-bin/account/modifyheadimage?access_token='.$authorizer_access_token;

            $modifyHeadImageResult = $this->curl_post_https($modifyHeadImageUrl,json_encode($modifyHeadImage,JSON_UNESCAPED_UNICODE));

            $modifyHeadImageResult = json_decode($modifyHeadImageResult,true);
            if($modifyHeadImageResult['errcode'] == 0){
                $authorizerAppidInfo = DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $this->app_id,'AuthorizerAppid' => $requestAllData['authorizer_appid']])->first();
                if(!empty($authorizerAppidInfo)){
                    $updateAuthorizerAppid['applet_avatar'] = $requestAllData['path'];
                    $updateAuthorizerAppid['updated_at']    = date("Y-m-d H:i:s",time());
                    $updateAuthorizerAppidResult = DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $this->app_id,'AuthorizerAppid' => $requestAllData['authorizer_appid']])->update($updateAuthorizerAppid);
                    if(!$updateAuthorizerAppidResult){
                        return $this->responseDataJson(202,"更新小程序数据库名称信息失败");
                    }
                }
                return $this->responseDataJson(200,"修改头像成功");
            }else{
                $errmsg = $this->getCodeMessage($modifyHeadImageResult['errcode']);
                return $this->responseDataJson($modifyHeadImageResult['errcode'],$errmsg ? $errmsg : "修改头像:".$modifyHeadImageResult['errcode'].":".$modifyHeadImageResult['errmsg']);
            }
        }else{
            return $this->responseDataJson(202,$authorizerTokenResult['message']);
        }
    }

    /**
     * 修改服务器域名
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateServerDomain(Request $request){
        $requestAllData  = $request->all();

        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }
        if(!isset($requestAllData['domain']) || empty($requestAllData['domain'])){
            return $this->responseDataJson(202,"服务器域名不可为空");
        }

        $domain = explode(",",$requestAllData['domain']);

        $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$requestAllData['authorizer_appid'],$requestAllData['refresh_token']);
        if($authorizerTokenResult['status'] == 200) {
            $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];
            //设置服务器域名
            $settingServerDomain = [
                "action"            => "add",
                "requestdomain"     => $domain,
                "wsrequestdomain"   => [],
                "uploaddomain"      => $domain,
                "downloaddomain"    => $domain
            ];
            $requestDomainUrl = "https://api.weixin.qq.com/wxa/modify_domain?access_token=".$authorizer_access_token;
            $requestDomainResult = $this->curl_post_https($requestDomainUrl,json_encode($settingServerDomain,JSON_UNESCAPED_UNICODE));
            $requestDomainResult = json_decode($requestDomainResult,true);
            if($requestDomainResult['errcode'] == 0){
                return $this->responseDataJson(200,"修改成功");
            }else{
                $errmsg = $this->getCodeMessage($requestDomainResult['errcode']);
                return $this->responseDataJson(202,$errmsg ? $errmsg : $requestDomainResult['errcode'].":".$authorizerTokenResult['message']);
            }
        }else{
            return $this->responseDataJson(202,$authorizerTokenResult['message']);
        }
    }

    /**
     * 提交审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function submit_audit(Request $request){
        $requestAllData  = $request->all();

        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }

        if(!isset($requestAllData['version_desc']) || empty($requestAllData['version_desc'])){
            return $this->responseDataJson(202,"版本描述不可为空");
        }

        $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$requestAllData['authorizer_appid'],$requestAllData['refresh_token']);
        if($authorizerTokenResult['status'] == 200){

            $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];

            $submitAuditRequestData = [
                "version_desc" => $requestAllData['version_desc'],
            ];
            $submitAuditRequestUrl  = "https://api.weixin.qq.com/wxa/submit_audit?access_token=".$authorizer_access_token;

            $submitAuditResult      = $this->curl_post_https($submitAuditRequestUrl,json_encode($submitAuditRequestData,JSON_UNESCAPED_UNICODE));

            $submitAuditResult      = json_decode($submitAuditResult,true);

            if($submitAuditResult['errcode'] == 0){
                return $this->responseDataJson(200,"提交审核成功，请等待微信官方通知");
            }else{
                $errmsg = $this->getCodeMessage($submitAuditResult['errcode']);
                return $this->responseDataJson(202,$errmsg ? $errmsg : $submitAuditResult['errcode'].":".$submitAuditResult['errmsg']);
            }
        }else{
            return $this->responseDataJson(202,$authorizerTokenResult['message']);
        }
    }


    /**
     * 发布已通过审核的小程序
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function releaseApplet(Request $request){
        $requestAllData  = $request->all();

        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }

        $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$requestAllData['authorizer_appid'],$requestAllData['refresh_token']);
        if($authorizerTokenResult['status'] == 200){

            $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];

            $submitAuditRequestUrl  = "https://api.weixin.qq.com/wxa/release?access_token=".$authorizer_access_token;

            $submitAuditResult      = $this->curl_post_https($submitAuditRequestUrl,"{}");

            $submitAuditResult      = json_decode($submitAuditResult,true);

            if($submitAuditResult['errcode'] == 0){
                return $this->responseDataJson(200,"发布成功");
            }else{
                $errmsg = $this->getCodeMessage($submitAuditResult['errcode']);
                return $this->responseDataJson(202,$errmsg ? $errmsg : $submitAuditResult['errcode'].":".$submitAuditResult['errmsg']);
            }
        }else{
            return $this->responseDataJson(202,$authorizerTokenResult['message']);
        }
    }

    /**
     * 查询服务商的当月提审限额（quota）和加急次数
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function queryQuota(Request $request){
        $requestAllData  = $request->all();

        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }

        $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$requestAllData['authorizer_appid'],$requestAllData['refresh_token']);
        if($authorizerTokenResult['status'] == 200){

            $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];

            $submitAuditRequestUrl  = "https://api.weixin.qq.com/wxa/queryquota?access_token=".$authorizer_access_token;

            $submitAuditResult      = $this->curl_post_https($submitAuditRequestUrl,"{}");

            $submitAuditResult      = json_decode($submitAuditResult,true);

            if($submitAuditResult['errcode'] == 0){
                $response_data['rest'] = $submitAuditResult['rest'];
                $response_data['limit'] = $submitAuditResult['limit'];
                $response_data['speedup_rest'] = $submitAuditResult['speedup_rest'];
                $response_data['speedup_limit'] = $submitAuditResult['speedup_limit'];
                return $this->responseDataJson(200,"查询成功",$response_data);
            }else{
                $errmsg = $this->getCodeMessage($submitAuditResult['errcode']);
                return $this->responseDataJson(202,$errmsg ? $errmsg : $submitAuditResult['errcode'].":".$submitAuditResult['errmsg']);
            }
        }else{
            return $this->responseDataJson(202,$authorizerTokenResult['message']);
        }
    }

    //订阅消息设置

    /**
     * 获取当前帐号所设置的类目信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getWeChatCateGory(Request $request){
        $requestAllData  = $request->all();

        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }

        $refresh_token = strstr($requestAllData['refresh_token'],"@@@");
        if(!$refresh_token){
            $requestAllData['refresh_token'] = str_replace("@@","@@@",$requestAllData['refresh_token']);
        }

        if(!isset($requestAllData['type']) || empty($requestAllData['type'])){
            return $this->responseDataJson(202,"type不可为空");
        }

        $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$requestAllData['authorizer_appid'],$requestAllData['refresh_token']);

        if($authorizerTokenResult['status'] == 200){

            $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];

            $result = $this->getCateGory($authorizer_access_token,$requestAllData);

            if($requestAllData['type'] == 2){

                if($result['status'] == 200){
                    return response()->json([
                        'status'  => 200,
                        'message' => $result['message'],
                        'data'    => isset($result['data']) ? $result['data'] : [],
                        'total_count' => $result['count'],
                        'page'    => (int)$requestAllData['page'],
                        't'       => (int)$requestAllData['count'],
                    ]);
                }else{
                    return response()->json([
                        'status'  => 202,
                        'message' => $result['message'],
                        'data'    => [],
                        'total_count' => 0,
                        'page'    => (int)$requestAllData['page'],
                        't'       => (int)$requestAllData['count'],
                    ]);
                }

            }else{
                if($result['status'] == 200){
                    return $this->responseDataJson(200,$result['message'],$result['data']);
                }else{
                    return $this->responseDataJson(202,$result['message']);
                }
            }
        }else{
            return $this->responseDataJson(202,$authorizerTokenResult['message']);
        }
    }

    /**
     * 封装 获取当前帐号所设置的类目信息
     * @param $access_token
     *        第三方平台接口调用令牌authorizer_access_token
     * @param $requestData
     *        请求的数据集合
     * @return array
     */
    public function getCateGory($access_token,$requestData){

        if($requestData['type'] == 1){

            //获取当前帐号所设置的类目信息
            //本接口用于获取小程序帐号当前所设置的类目。使用过程中如遇到问题，可在开放平台服务商专区发帖交流。

            $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/getcategory?access_token='.$access_token;
            $getCateGoryResult = $this->curl_get_https($url);
            $getCateGoryResult = json_decode($getCateGoryResult,true);
            if($getCateGoryResult['errcode'] == 0){
                return ['status' => 200,'message' => '查询成功', 'data' => $getCateGoryResult['data']];
            }else{
                $errmsg = $this->getCodeMessage($getCateGoryResult['errcode']);
                return ['status' => 202,'message' => $errmsg ? $errmsg : $getCateGoryResult['errcode'].":".$getCateGoryResult['errmsg']];
            }

        }else if($requestData['type'] == 2){

            //获取模板标题列表 , 并且 获取模板标题下的关键词库
            //本接口用于获取小程序订阅消息的模板库标题列表

            $page = $requestData['page'] - 1;
            $count = isset($requestData['count']) ? $requestData['count'] : 10;
            $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/getpubtemplatetitles?access_token='.$access_token.'&ids='.$requestData['ids'].'&start='.$page.'&limit='.$count;
            $getCateGoryResult = $this->curl_get_https($url);
            $getCateGoryResult = json_decode($getCateGoryResult,true);
            if($getCateGoryResult['errcode'] == 0){

                $template = DB::table("customerapplets_template_infos")->select("applet_id","categoryId","tid","template_id")->where(
                    ['applet_id' => $requestData['authorizer_appid'],'type' => 1,'status' => 1]
                )->get();

                foreach ($getCateGoryResult['data'] as $key => $val){
                    $getCateGoryResult['data'][$key]['type_name'] = $val['type'] == 2 ? "一次性订阅" : "长期订阅";
                    $getCateGoryResult['data'][$key]['status'] = 2;
                    $getCateGoryResult['data'][$key]['template_id'] = "";
                    foreach ($template as $k => $v){
                        if($val['categoryId'] == $v->categoryId && $val['tid'] == $v->tid){
                            $getCateGoryResult['data'][$key]['status'] = 1;
                            $getCateGoryResult['data'][$key]['template_id'] = $v->template_id;
                        }
                    }
                }

                return ['status' => 200,'message' => '查询成功', 'data' => $getCateGoryResult['data'],'count' => $getCateGoryResult['count']];
            }else{
                $errmsg = $this->getCodeMessage($getCateGoryResult['errcode']);
                return ['status' => 202,'message' => $errmsg ? $errmsg : $getCateGoryResult['errcode'].":".$getCateGoryResult['errmsg']];
            }

        }else if($requestData['type'] == 3){
            //组合模板并添加到个人模板库
            $kidList = [];
            if(isset($requestData['kidList'])){
                $kidList = explode(",",$requestData['kidList']);
            }
            $checkwxverifynickname = [
                "tid"       => $requestData['tid'],
                "kidList"   => $kidList,
                "sceneDesc" => $requestData['sceneDesc'],
            ];
            $checkwxverifynicknameUrl    = 'https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token='.$access_token;
            $checkwxverifynicknameResult = $this->curl_post_https($checkwxverifynicknameUrl,json_encode($checkwxverifynickname,JSON_UNESCAPED_UNICODE),["Content-Type: application/json"]);
            $checkwxverifynicknameResult = json_decode($checkwxverifynicknameResult,true);
            if($checkwxverifynicknameResult['errcode'] == 0){

                $template = DB::table("customerapplets_template_infos")->where(
                    ['applet_id' => $requestData['authorizer_appid'],'type' => 1,'categoryId' => $requestData['categoryId'],'tid' => $requestData['tid']]
                )->first();

                $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token='.$access_token;
                $getCateGoryResult = $this->curl_get_https($url);
                $getCateGoryResult = json_decode($getCateGoryResult,true);
                if($getCateGoryResult['errcode'] == 0){
                    $templateKeyword = "";
                    $templateList = $getCateGoryResult['data'];
                    foreach ($templateList as $key => $val){
                        if($val['priTmplId'] == $checkwxverifynicknameResult['priTmplId']){
                            $templateKeyword = $val['content'];
                        }
                    }
                    if(!empty($template)){
                        //根据该模板状态进行判断，1：说明在使用
                        if($template->status == 1){
                            //已添加过该模板,需要更新下模板id
                            DB::table("customerapplets_template_infos")->where(
                                ['applet_id' => $requestData['authorizer_appid'],'type' => 1,'categoryId' => $requestData['categoryId'],'tid' => $requestData['tid']]
                            )->update([
                                'template_id' => $checkwxverifynicknameResult['priTmplId'],
                                'template_keyword' => $templateKeyword,
                                'updated_at' => date('Y-m-d H:i:s',time()),
                            ]);
                        }else{
                            //说明之前删除过该模板，这次添加直接更新下状态就可以了
                            DB::table("customerapplets_template_infos")->where(
                                ['applet_id' => $requestData['authorizer_appid'],'type' => 1,'categoryId' => $requestData['categoryId'],'tid' => $requestData['tid']]
                            )->update([
                                'status'     => 1,
                                'template_id' => $checkwxverifynicknameResult['priTmplId'],
                                'template_keyword' => $templateKeyword,
                                'updated_at' => date('Y-m-d H:i:s',time()),
                            ]);
                        }
                    }else{
                        //将使用的模板保存到数据库进行记录
                        DB::table("customerapplets_template_infos")->insert([
                            'applet_id'  => $requestData['authorizer_appid'],
                            'type'       => 1,
                            'categoryId' => $requestData['categoryId'],
                            'tid'        => $requestData['tid'],
                            'title'      => $requestData['title'],
                            'status'     => 1,
                            'template_id'=> $checkwxverifynicknameResult['priTmplId'],
                            'template_keyword' => $templateKeyword,
                            'created_at' => date('Y-m-d H:i:s',time()),
                            'updated_at' => date('Y-m-d H:i:s',time()),
                        ]);
                    }
                    return ['status' => 200,'message' => '添加成功', 'data' => $checkwxverifynicknameResult['priTmplId']];
                }else{
                    $errmsg = $this->getCodeMessage($getCateGoryResult['errcode']);
                    return ['status' => 202,'message' => $errmsg ? $errmsg : $getCateGoryResult['errcode'].":".$getCateGoryResult['errmsg']];
                }
            }else{
                $errmsg = $this->getCodeMessage($checkwxverifynicknameResult['errcode']);
                return ['status' => 202,'message' => $errmsg ? $errmsg : $checkwxverifynicknameResult['errcode'].":".$checkwxverifynicknameResult['errmsg']];
            }

        }else if($requestData['type'] == 4){
            //获取帐号下的模板列表

            $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token='.$access_token;
            $getCateGoryResult = $this->curl_get_https($url);
            $getCateGoryResult = json_decode($getCateGoryResult,true);
            if($getCateGoryResult['errcode'] == 0){
                return ['status' => 200,'message' => '查询成功', 'data' => $getCateGoryResult['data']];
            }else{
                $errmsg = $this->getCodeMessage($getCateGoryResult['errcode']);
                return ['status' => 202,'message' => $errmsg ? $errmsg : $getCateGoryResult['errcode'].":".$getCateGoryResult['errmsg']];
            }
        }else if($requestData['type'] == 5){
            //删除帐号下的某个模板

            $template = DB::table("customerapplets_template_infos")->where(
                ['applet_id' => $requestData['authorizer_appid'],'type' => 1,'tid' => $requestData['tid'],'template_id' => $requestData['template_id']]
            )->first();

            if(!empty($template)){
                $checkwxverifynickname = [
                    'priTmplId' => $template->template_id,
                ];
                $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate?access_token='.$access_token;
                $getCateGoryResult = $this->curl_post_https($url,json_encode($checkwxverifynickname,JSON_UNESCAPED_UNICODE),["Content-Type: application/json"]);
                $getCateGoryResult = json_decode($getCateGoryResult,true);
                if($getCateGoryResult['errcode'] == 0){

                    if($template->status == 1){
                        //说明正常使用，可以删除
                        DB::table("customerapplets_template_infos")->where(
                            ['applet_id' => $requestData['authorizer_appid'],'type' => 1,'tid' => $requestData['tid'],'template_id' => $requestData['template_id']]
                        )->update([
                            'status'     => 2,
                            'updated_at' => date('Y-m-d H:i:s',time()),
                        ]);
                    }

                    return ['status' => 200,'message' => '删除成功', 'data' => ''];
                }else{
                    $errmsg = $this->getCodeMessage($getCateGoryResult['errcode']);
                    return ['status' => 202,'message' => $errmsg ? $errmsg : $getCateGoryResult['errcode'].":".$getCateGoryResult['errmsg']];
                }
            }else{
                return ['status' => 202,'message' => '未添加该模板'];
            }
        }else if($requestData['type'] == 6){
            //获取模板标题下的关键词库

            $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/getpubtemplatekeywords?access_token='.$access_token.'&tid='.$requestData['tid'];

            $keywordResult = $this->curl_get_https($url);

            $keywordResult = json_decode($keywordResult,true);

            if($keywordResult['errcode'] == 0){
                return ['status' => 200,'message' => '查询成功', 'data' => $keywordResult['data']];
            }else{
                $errmsg = $this->getCodeMessage($keywordResult['errcode']);
                return ['status' => 202,'message' => $errmsg ? $errmsg : $keywordResult['errcode'].":".$keywordResult['errmsg']];
            }

        }
    }

    //类目管理

    /**
     * 获取可以设置的所有类目
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAllCategories(Request $request){
        $requestAllData  = $request->all();
        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }
        $refresh_token = strstr($requestAllData['refresh_token'],"@@@");
        if(!$refresh_token){
            $requestAllData['refresh_token'] = str_replace("@@","@@@",$requestAllData['refresh_token']);
        }

        $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$requestAllData['authorizer_appid'],$requestAllData['refresh_token']);

        if($authorizerTokenResult['status'] == 200){
            $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];

            //获取可以设置的所有类目

            $url = 'https://api.weixin.qq.com/cgi-bin/wxopen/getallcategories?access_token='.$authorizer_access_token;
            $getCateGoryResult = $this->curl_get_https($url);
            $getCateGoryResult = json_decode($getCateGoryResult,true);
            if($getCateGoryResult['errcode'] == 0){
                return $this->responseDataJson(200,'查询成功',$getCateGoryResult['categories_list']);
            }else{
                $errmsg = $this->getCodeMessage($getCateGoryResult['errcode']);
                return $this->responseDataJson(202,$errmsg ? $errmsg : $getCateGoryResult['errcode'].":".$getCateGoryResult['errmsg']);
            }
        }else{
            return $this->responseDataJson(202,$authorizerTokenResult['message']);
        }
    }

    /**
     * 获取已设置的所有类目
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSetCateGory(Request $request){
        $requestAllData  = $request->all();
        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }
        $refresh_token = strstr($requestAllData['refresh_token'],"@@@");
        if(!$refresh_token){
            $requestAllData['refresh_token'] = str_replace("@@","@@@",$requestAllData['refresh_token']);
        }

        $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$requestAllData['authorizer_appid'],$requestAllData['refresh_token']);

        if($authorizerTokenResult['status'] == 200){
            $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];

            //获取已设置的所有类目

            $url = 'https://api.weixin.qq.com/cgi-bin/wxopen/getcategory?access_token='.$authorizer_access_token;
            $getCateGoryResult = $this->curl_get_https($url);
            $getCateGoryResult = json_decode($getCateGoryResult,true);
            if($getCateGoryResult['errcode'] == 0){
                return response()->json([
                    'status'  => 200,
                    'message' => '查询成功',
                    'data'    => isset($getCateGoryResult['categories']) ? $getCateGoryResult['categories'] : [],
                    'total_count' => count($getCateGoryResult['categories']),
                    'page'    => (int)$requestAllData['page'],
                    't'       => (int)$requestAllData['count'],
                ]);
            }else{
                $errmsg = $this->getCodeMessage($getCateGoryResult['errcode']);
                return response()->json([
                    'status'  => 202,
                    'message' => $errmsg ? $errmsg : $getCateGoryResult['errcode'].":".$getCateGoryResult['errmsg'],
                    'data'    => [],
                    'total_count' => 0,
                    'page'    => (int)$requestAllData['page'],
                    't'       => (int)$requestAllData['count'],
                ]);
            }
        }else{
            return $this->responseDataJson(202,$authorizerTokenResult['message']);
        }
    }

    /**
     * 添加类目
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addCateGory(Request $request){
        $requestAllData  = $request->all();
        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }
        if(!isset($requestAllData['first']) || empty($requestAllData['first'])){
            return $this->responseDataJson(202,"一级类目不可为空");
        }
        if(!isset($requestAllData['second']) || empty($requestAllData['second'])){
            return $this->responseDataJson(202,"二级类目不可为空");
        }
        $refresh_token = strstr($requestAllData['refresh_token'],"@@@");
        if(!$refresh_token){
            $requestAllData['refresh_token'] = str_replace("@@","@@@",$requestAllData['refresh_token']);
        }

        $cerTiCateData = [];
        if(!empty($requestAllData['certicates'])){
            foreach ($requestAllData['certicates'] as $key => $val){
                $cerTiCateDataFirst['key'] = $val[0];
                $cerTiCateDataFirst['value'] = $val[1];
                array_push($cerTiCateData,$cerTiCateDataFirst);
            }
        }

        $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$requestAllData['authorizer_appid'],$requestAllData['refresh_token']);

        if($authorizerTokenResult['status'] == 200){
            $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];
            //添加类目
            $categories = [
                'categories' => [
                    ["first" => $requestAllData['first'],"second" => $requestAllData['second'],"certicates" => $cerTiCateData]
                ]
            ];
            $url = 'https://api.weixin.qq.com/cgi-bin/wxopen/addcategory?access_token='.$authorizer_access_token;
            $getCateGoryResult = $this->curl_post_https($url,json_encode($categories,JSON_UNESCAPED_UNICODE));
            $getCateGoryResult = json_decode($getCateGoryResult,true);
            if($getCateGoryResult['errcode'] == 0){
                return $this->responseDataJson(200,'添加成功');
            }else{
                $errmsg = $this->getCodeMessage($getCateGoryResult['errcode']);
                return $this->responseDataJson(202,$errmsg ? $errmsg : $getCateGoryResult['errcode'].":".$getCateGoryResult['errmsg']);
            }
        }else{
            return $this->responseDataJson(202,$authorizerTokenResult['message']);
        }
    }

    /**
     * 删除类目
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteCateGory(Request $request){
        $requestAllData  = $request->all();
        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }
        if(!isset($requestAllData['first']) || empty($requestAllData['first'])){
            return $this->responseDataJson(202,"一级类目ID不可为空");
        }
        if(!isset($requestAllData['second']) || empty($requestAllData['second'])){
            return $this->responseDataJson(202,"二级类目ID不可为空");
        }

        $refresh_token = strstr($requestAllData['refresh_token'],"@@@");
        if(!$refresh_token){
            $requestAllData['refresh_token'] = str_replace("@@","@@@",$requestAllData['refresh_token']);
        }

        $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$requestAllData['authorizer_appid'],$requestAllData['refresh_token']);

        if($authorizerTokenResult['status'] == 200){
            $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];
            //删除类目

            $categories = [
                "first" => intval($requestAllData['first']),
                "second"=> intval($requestAllData['second'])
            ];

            $url = 'https://api.weixin.qq.com/cgi-bin/wxopen/deletecategory?access_token='.$authorizer_access_token;

            $getCateGoryResult = $this->curl_post_https($url,json_encode($categories,JSON_UNESCAPED_UNICODE));

            $getCateGoryResult = json_decode($getCateGoryResult,true);
            if($getCateGoryResult['errcode'] == 0){
                return $this->responseDataJson(200,'添加成功');
            }else{
                $errmsg = $this->getCodeMessage($getCateGoryResult['errcode']);
                return $this->responseDataJson(202,$errmsg ? $errmsg : $getCateGoryResult['errcode'].":".$getCateGoryResult['errmsg']);
            }
        }else{
            return $this->responseDataJson(202,$authorizerTokenResult['message']);
        }
    }


    /**
     * 查询模板应用的位置
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAllUseIndex(Request $request){
        $requestAllData  = $request->all();
        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }
        if(!isset($requestAllData['is_select']) || empty($requestAllData['is_select'])){
            return $this->responseDataJson(202,"is_select不可为空");
        }
        $templatePages = DB::table("customerapplets_template_pages")->get();

        //is_select == 1说明需要查找下数据库中有没有存储过这个模板消息
        if($requestAllData['is_select'] == 1){
            //说明需要查找
            foreach ($templatePages as $key => $val){
                $templateInfo = DB::table("customerapplets_template_infos")->where(['applet_id' => $requestAllData['authorizer_appid'],'type' => 1,'status' => 1])->where("template_use_index","like","%".$val->id."%")->first();
                if(!empty($templateInfo)){
                    $val->is_use = true;
                }else{
                    $val->is_use = false;
                }
            }
        }
        return $this->responseDataJson(200,'查询成功',$templatePages);
    }

    /**
     * 获取查询模板应用的位置列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getTemplateIndexListData(Request $request){
        $requestAllData = $request->all();
        $page = $requestAllData['page'];
        $count = isset($requestAllData['count']) ? $requestAllData['count'] : 10;
        $total_count = DB::table("customerapplets_template_pages")->count();
        $result = DB::table("customerapplets_template_pages")->paginate(10)->toArray();
        return response()->json([
            'status'  => 200,
            'message' => "请求成功",
            'data'    => isset($result) ? $result['data'] : [],
            'total_count' => $total_count,
            'page'    => (int)$page,
            't'       => (int)$count,
        ]);
    }

    /**
     * 添加模板应用的位置
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addUserIndex(Request $request){
        $requestAllData  = $request->all();
        if(!isset($requestAllData['title']) || empty($requestAllData['title'])){
            return $this->responseDataJson(202,"title不可为空");
        }
        $result = DB::table("customerapplets_template_pages")->insert([
            'title' => $requestAllData['title'],
            'pages' => isset($requestAllData['pages']) ? $requestAllData['pages'] : "",
            'created_at' => date("Y-m-d H:i:s",time()),
            'updated_at' => date("Y-m-d H:i:s",time()),
        ]);
        if($result){
            return $this->responseDataJson(200,'保存成功');
        }else{
            return $this->responseDataJson(202,'保存失败');
        }
    }

    /**
     * 修改模板应用的位置
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateUserIndex(Request $request){
        $requestAllData  = $request->all();
        if(!isset($requestAllData['title']) || empty($requestAllData['title'])){
            return $this->responseDataJson(202,"title不可为空");
        }
        if(!isset($requestAllData['id']) || empty($requestAllData['id'])){
            return $this->responseDataJson(202,"id不可为空");
        }
        $result = DB::table("customerapplets_template_pages")->where(['id' => $requestAllData['id']])->update([
            'title' => $requestAllData['title'],
            'pages' => isset($requestAllData['pages']) ? $requestAllData['pages'] : "",
            'updated_at' => date("Y-m-d H:i:s",time()),
        ]);
        if($result){
            return $this->responseDataJson(200,'修改成功');
        }else{
            return $this->responseDataJson(202,'修改失败');
        }
    }

    /**
     * 修改小程序的模板所在的位置
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateTemplateUseIndex(Request $request){
        //需要判断每一个位置的使用的模板数量不能超过三个(微信的限制)
        $requestAllData  = $request->all();
        if(!isset($requestAllData['authorizer_appid']) || empty($requestAllData['authorizer_appid'])){
            return $this->responseDataJson(202,"授权方小程序appid不可为空");
        }
        if(!isset($requestAllData['refresh_token']) || empty($requestAllData['refresh_token'])){
            return $this->responseDataJson(202,"refresh_token不可为空");
        }
        if(!isset($requestAllData['template_id']) || empty($requestAllData['template_id'])){
            return $this->responseDataJson(202,"template_id不可为空");
        }

        if(!isset($requestAllData['use_index']) || empty($requestAllData['use_index'])){
            $useIndex = [];
        }else{
            $useIndex = $requestAllData['use_index'];
        }

        if(!empty($useIndex) && count($useIndex) > 0){
            $key = true;
            $title = "";
            foreach ($useIndex as $key => $val){
                $result = DB::table("customerapplets_template_infos")->where([
                    'applet_id' => $requestAllData['authorizer_appid'],
                    'type'      => 1,
                    'template_id' => $requestAllData['template_id']
                ])->where('template_use_index','like',"%".$val."%")->get();
                if(count($result) > 3){
                    $key = false;
                    $template_pages = DB::table("customerapplets_template_pages")->select("title")->where(['id' => $val])->first();
                    $title = $template_pages->title;
                }
            }
            if(!$key){
                return $this->responseDataJson(202,$title."，该位置已经超过三个模板！");
            }
            $result = DB::table("customerapplets_template_infos")->where([
                'applet_id' => $requestAllData['authorizer_appid'],
                'type'      => 1,
                'template_id' => $requestAllData['template_id']
            ])->update([
                'template_use_index' => implode(",",$useIndex),
                'updated_at'         => date("Y-m-d H:i:s",time())
            ]);
            if($result){
                return $this->responseDataJson(200,'修改成功');
            }else{
                return $this->responseDataJson(202,'修改失败');
            }
        }else{
            $result = DB::table("customerapplets_template_infos")->where([
                'applet_id' => $requestAllData['authorizer_appid'],
                'type'      => 1,
                'template_id' => $requestAllData['template_id']
            ])->update([
                'template_use_index' => "",
                'updated_at'         => date("Y-m-d H:i:s",time())
            ]);
            if($result){
                return $this->responseDataJson(200,'修改成功');
            }else{
                return $this->responseDataJson(202,'修改失败');
            }
        }
    }

    /**
     * 发送模板消息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendTemplateInfo(Request $request){
        $requestAllData  = $request->all();
        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(202,"store_id不可为空");
        }
        if(!isset($requestAllData['type']) || empty($requestAllData['type'])){
            return $this->responseDataJson(202,"type不可为空");
        }
        if(!isset($requestAllData['sendTemplateData']) || empty($requestAllData['sendTemplateData'])){
            return $this->responseDataJson(202,"模板消息内容不可为空");
        }
        if(!isset($requestAllData['sendUser']) || empty($requestAllData['sendUser'])){
            return $this->responseDataJson(202,"接收人员不可为空");
        }
        if(!isset($requestAllData['template_id']) || empty($requestAllData['template_id'])){
            return $this->responseDataJson(202,"模板id不可为空");
        }

        if($requestAllData['type'] == 1){
            //发送微信模板消息
            $storeInfo = DB::table("merchant_store_appid_secrets")
                ->select("wechat_appid","alipay_appid")
                ->where(['store_id' => $requestAllData['store_id']])->first();
            if(empty($storeInfo) || empty($storeInfo->wechat_appid)){
                return $this->responseDataJson(202,"请先完善该门店小程序信息");
            }

            $authorizeAppId = DB::table("customerapplets_authorize_appids")->where([
                't_appid'         => $this->app_id,
                'applet_type'     => 1,
                'AuthorizerAppid' => $storeInfo->wechat_appid,
            ])->first();

            if(empty($authorizeAppId) || empty($authorizeAppId->authorizer_refresh_token)){
                return $this->responseDataJson(202,"未查找到小程序授权第三方信息");
            }

            $authorizerTokenResult = $this->getAuthorizerToken($this->app_id,$storeInfo->wechat_appid,$authorizeAppId->authorizer_refresh_token);

            if($authorizerTokenResult['status'] == 200){
                $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token'];
            }else{
                return $this->responseDataJson(202,$authorizerTokenResult['message']);
            }

            $templateData = [];
            foreach ($requestAllData['sendTemplateData'] as $key => $val){
                $templateData[$val[0]]['value'] = $val[1];
            }

            $key = false;
            $sendUserTemplateData = [];

            //发送成功数量的人数
            $successNumber = 0;
            //发送失败数量的人数
            $errorNumber   = 0;

            //给微信小程序用户发送
            foreach ($requestAllData['sendUser'] as $key => $val){
                $result = $this->messageSubscribeSend($val,$requestAllData['template_id'],$templateData,$requestAllData['store_id'],$authorizer_access_token);

//                $sendUserTemplateDataFirst['user_system_id'] = $val;
//                $sendUserTemplateDataFirst['type']           = 1;
//                $sendUserTemplateDataFirst['store_id']       = $requestAllData['store_id'];
//                $sendUserTemplateDataFirst['template_id']    = $requestAllData['template_id'];
//                $sendUserTemplateDataFirst['created_at']     = date("Y-m-d H:i:s",time());
//                $sendUserTemplateDataFirst['updated_at']     = date("Y-m-d H:i:s",time());

                if($result['status'] == 200){
                    $key = true;
                    $successNumber = $successNumber + 1;
//                    $sendUserTemplateDataFirst['message']    = "";
                }else{
                    $errorNumber   = $errorNumber   + 1;
//                    $sendUserTemplateDataFirst['message']    = $result['message'];
                }
//                array_push($sendUserTemplateData,$sendUserTemplateDataFirst);
            }

            $message = "发送成功：".$successNumber.";发送失败：".$errorNumber;

            if($key){
                return $this->responseDataJson(200,$message);
            }else{
                return $this->responseDataJson(202,$message);
            }
        }else{
            //发送支付宝模板消息
            $storeInfo = DB::table("merchant_store_appid_secrets")
                ->select("wechat_appid","alipay_appid")
                ->where(['store_id' => $requestAllData['store_id']])->first();
            if(empty($storeInfo) || empty($storeInfo->alipay_appid)){
                return $this->responseDataJson(202,"请先完善该门店小程序信息");
            }

            $authorizeAppId = DB::table("customerapplets_authorize_appids")->where([
                't_appid'         => config("api.aliPay_applet_id"),
                'applet_type'     => 2,
                'AuthorizerAppid' => $storeInfo->alipay_appid,
            ])->first();

            if(empty($authorizeAppId) || empty($authorizeAppId->authorizer_refresh_token)){
                return $this->responseDataJson(202,"未查找到小程序授权第三方信息");
            }

            $templateData = [];
            foreach ($requestAllData['sendTemplateData'] as $key => $val){
                $templateData[$val[0]]['value'] = $val[1];
            }

            $key = false;
            $sendUserTemplateData = [];

            //发送成功数量的人数
            $successNumber = 0;
            //发送失败数量的人数
            $errorNumber   = 0;

            //给微信小程序用户发送
            $aliPayTicketController = new AliPayTicketController();
            $weekDate = date("Y-m-d H:i:s",strtotime("-7 day"));

            $nowDate = date("Y-m-d H:i:s",time());

            foreach ($requestAllData['sendUser'] as $key => $val){
                $formId = DB::table("customerapplets_form_ids")
                    ->select("id","form_id","count")
                    ->where(['store_id'  => $requestAllData['store_id'], 'system_id' => $val, 'type' => 2])
                    ->where("count","<>",3)
                    ->where("created_at",">",$weekDate)
                    ->first();

//                $sendUserTemplateDataFirst['user_system_id'] = $val;
//                $sendUserTemplateDataFirst['type']           = 2;
//                $sendUserTemplateDataFirst['store_id']       = $requestAllData['store_id'];
//                $sendUserTemplateDataFirst['template_id']    = $requestAllData['template_id'];
//                $sendUserTemplateDataFirst['created_at']     = $nowDate;
//                $sendUserTemplateDataFirst['updated_at']     = $nowDate;

                if(!empty($formId)){
                    $result = $aliPayTicketController->aliPayOpenAppMiniTemplateMessageSend(
                        $authorizeAppId->t_appid,
                        $authorizeAppId->AuthorizationCode,
                        $requestAllData['store_id'],
                        $val,
                        $formId->form_id,
                        $requestAllData['template_id'],
                        $templateData
                    );
                    if($result['status'] == 200){
                        $key = true;

                        DB::table("customerapplets_form_ids")
                            ->where(['id' => $formId->id,'store_id'  => $requestAllData['store_id'], 'system_id' => $val, 'type' => 2])
                            ->update([
                                'count'      => intval($formId->count) + 1,
                                'updated_at' => $nowDate
                            ]);

                        $successNumber = $successNumber + 1;

//                        $sendUserTemplateDataFirst['message']    = "";
                    }else{
                        $errorNumber   = $errorNumber   + 1;

//                        $sendUserTemplateDataFirst['message']    = $result['message'];
                    }
                }else{
//                    $sendUserTemplateDataFirst['message']    = "该支付宝用户的formId已经使用完或者暂无formId";
                }
//                array_push($sendUserTemplateData,$sendUserTemplateDataFirst);
            }

            $message = "发送成功：".$successNumber.";发送失败：".$errorNumber;
            if($key){
                return $this->responseDataJson(200,$message);
            }else{
                return $this->responseDataJson(202,$message);
            }
        }
    }

    /**
     * 获取某一个位置的小程序模板消息id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAppletTemplateId(Request $request){
        $requestAllData  = $request->all();
        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(202,"store_id不可为空");
        }
        if(!isset($requestAllData['id']) || empty($requestAllData['id'])){
            return $this->responseDataJson(202,"id标识不可为空");
        }

        $storeInfo = DB::table("merchant_store_appid_secrets")
            ->select("wechat_appid","alipay_appid")
            ->where(['store_id' => $requestAllData['store_id']])->first();
        if(empty($storeInfo) || empty($storeInfo->wechat_appid)){
            return $this->responseDataJson(202,"请先完善该门店小程序信息");
        }
        //微信小程序一次性订阅消息数量有限，最多只能三个
        $result = DB::table("customerapplets_template_infos")
            ->select("id","applet_id","type","template_id","status")
            ->where(['applet_id' => $storeInfo->wechat_appid, 'type' => 1, 'status' => 1])
            ->where("template_use_index","like","%".$requestAllData['id']."%")->orderBy("created_at","desc")
            ->limit(3)->get();
        Log::info("getAppletTemplateId：".json_encode($result));
        return $this->responseDataJson(200,"请求成功",$result);
    }

    /**
     * 封装 发送模板消息
     * @param $toUserOpenId
     * @param $store_id
     * @param $access_token
     * @return array
     *
     * //$data = [
       // 'thing1' => ['value' => '商家优惠'],
       // 'thing3' => ['value' => '领券开始啦'],
       // 'thing4' => ['value' => '领券活动'],
       //];
     *
     */
    public function messageSubscribeSend($toUserOpenId,$templateId,$templateData,$store_id,$access_token){

        $params1 = [
            'touser'        => $toUserOpenId,
            'template_id'   => $templateId,
            'page'          => '/pages/index/index?store_id='.$store_id,
            'data'          => $templateData,
        ];

        $json_template = json_encode($params1);

        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;

        $getCateGoryResult = $this->curl_post_https($url,urldecode($json_template));

        $getCateGoryResult = json_decode($getCateGoryResult,true);
        Log::info($toUserOpenId."|".$templateId."|".json_encode($getCateGoryResult));

        if($getCateGoryResult['errcode'] == 0){
            return ['status' => 200,'message' => '发送成功', 'data' => ''];
        }else{
            $errmsg = $this->getCodeMessage($getCateGoryResult['errcode']);
            return ['status' => 202,'message' => $errmsg ? $errmsg : $getCateGoryResult['errcode'].":".$getCateGoryResult['errmsg']];
        }
    }


    /**
     * 获取微信小程序创建信息列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAppletsInfoListByStore(Request $request)
    {
        $store_id = $request->post('storeId', ''); //门店id
        $type = $request->post('type', 1); //小程序类型(1-微信;2-支付宝)

        $where = [];
        if ($store_id) {
            $storeObj = Store::where('store_id', $store_id)
                ->where('is_close', 0)
                ->where('is_delete', 0)
                ->first();
            if (!$storeObj) {
                return $this->responseDataJson(202, "门店不存在或状态异常");
            }
            $where[] = ['store_id', '=' , $store_id];
        }

        try {
            $infoObj = CustomerAppletsStore::where('type', $type)
                ->where($where)
                ->get();

            return $this->responseDataJson(200, "成功", $infoObj);
        } catch (\Exception $ex) {
            Log::info('获取微信小程序创建信息-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return $this->responseDataJson(-1, "获取微信小程序创建信息列表 Unknown error, please contact customer service");
        }
    }


    /**
     * 获取门店对应的小程序信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStoreAppletInfo(Request $request)
    {
        $store_id = $request->post('storeId', ''); //门店id

        try {
            $where = [];
            if ($store_id) {
                $storeObj = Store::where('store_id', $store_id)
                    ->where('is_close', 0)
                    ->where('is_delete', 0)
                    ->first();
                if (!$storeObj) {
                    return $this->responseDataJson(202, "门店不存在或状态异常");
                }

                $where[] = ['store_id', '=', $store_id];
            }

            $merchantStoreAppIdSecretResult = MerchantStoreAppidSecret::where($where)
                ->get();

            return $this->responseDataJson(200, "成功", $merchantStoreAppIdSecretResult);
        } catch (\Exception $ex) {
            Log::info('获取门店对应的小程序信息-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return $this->responseDataJson(-1, "获取门店对应的小程序信息 Unknown error, please contact customer service");
        }
    }


    /**
     * wx.login获取的code换取openid和SessionKey
     * @param Request $request
     * @return mixed
     */
    public function getSessionKeyOpenid(Request $request)
    {
        $code = $request->post('code', ''); //wx.login获取的code
        $store_id = $request->post('storeId', ''); //门店id

        if ( empty($code) || !isset($code) ) {
            return $this->responseDataJson(202, 'code参数缺乏');
        }

        if ( empty($store_id) || !isset($store_id) ) {
            return $this->responseDataJson(202, 'storeId参数缺乏');
        }

        try {
            $storeObj = Store::where('store_id', $store_id)
                ->where('is_close', 0)
                ->where('is_delete', 0)
                ->first();
            if (!$storeObj) {
                return $this->responseDataJson(202, "门店不存在或状态异常");
            }

            $merchantStoreAppidSecretObj = MerchantStoreAppidSecret::where('store_id', $store_id)->first();
            if (!$merchantStoreAppidSecretObj) {
                return $this->responseDataJson(202, "门店无小程序信息");
            }

            $Appid = $merchantStoreAppidSecretObj->wechat_appid; // 小程序appid
            $AppSecret = $merchantStoreAppidSecretObj->wechat_secret; // 小程序秘钥

            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$Appid."&secret=".$AppSecret."&js_code=".$code."&grant_type= authorization_code";
//            $handle = curl_init();
//            curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
//            curl_setopt($handle, CURLOPT_HEADER, 0);
//            curl_setopt($handle, CURLOPT_NOBODY, 0);
//            curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
//            curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
//            curl_setopt($handle, CURLOPT_URL, $url);
//            curl_setopt($handle, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
//            $data = curl_exec($handle);
//            curl_close($handle);
            $max_string = $this->curl_get($url);
//            Log::info('wx.login获取的code换取openid和SessionKey');
//            Log::info($max_string);
            $data = substr( $max_string, strpos($max_string, "{") );
//            Log::info($data);
            $resData = json_decode($data, true);
            $res = [];
            if ( isset($resData['errcode']) ) {
                $res['errcode'] = $resData['errcode'] ?? '-1';
                $res['errmsg'] = $resData['errmsg'] ?? '系统繁忙，请稍后重试';
            }
            elseif ( isset($resData['openid']) ) {
                $res['openid'] = $resData['openid'];
            }
            elseif ( isset($resData['session_key']) ) {
                $res['session_key'] = $resData['session_key'];
            }
            else {
                return $this->responseDataJson(202, '获取失败,请重新获取');
            }

            return $this->responseDataJson(200, '获取成功', $res);
        } catch (\Exception $ex) {
            Log::info('获取openid-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return $this->responseDataJson(-1, "获取openid Unknown error, please contact customer service");
        }
    }


    /**
     * 查询最新一次提交的审核状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getLatestAuditStatus(Request $request)
    {
        $authorizer_appid = $request->post('authorizerAppId', ''); //授权人APPID
        $refresh_token = $request->post('refreshToken', ''); //刷新token

        try {
            $newAppletsArray = [];

            $authorizerTokenResult = $this->getAuthorizerToken($this->app_id, $authorizer_appid, $refresh_token);
            if($authorizerTokenResult['status'] == 200){
                $authorizerToken = $authorizerTokenResult['data']['authorizer_access_token'];
                $url = 'https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token='.$authorizerToken;
                $getLatestGuditStatus = $this->curl_get_https($url);
                $getLatestGuditStatus = json_decode($getLatestGuditStatus,true);

                if($getLatestGuditStatus['errcode'] == 0){
                    $newAppletsArray['authorizer_appid_status'] = $getLatestGuditStatus['status'];
                    switch ($getLatestGuditStatus['status']){
                        case 0:
                            $newAppletsArray['authorizer_appid_status_desc'] = "审核成功";
                            break;
                        case 1:
                            $newAppletsArray['authorizer_appid_status_desc'] = "审核被拒绝";
                            $newAppletsArray['authorizer_appid_status_reason'] = $getLatestGuditStatus['reason'];
                            break;
                        case 2:
                            $newAppletsArray['authorizer_appid_status_desc'] = "审核中";
                            break;
                        case 3:
                            $newAppletsArray['authorizer_appid_status_desc'] = "已撤回";
                            break;
                        default:
                            $newAppletsArray['authorizer_appid_status_desc'] = "未发布审核";
                    }

                    return $this->responseDataJson(200, '成功', $newAppletsArray);
                } else {
                    return $this->responseDataJson(202, 'fail', $newAppletsArray);
                }
            } else {
                return $this->responseDataJson(202, 'fail', $newAppletsArray);
            }

        } catch (\Exception $ex) {
            Log::info('查询最新一次提交的审核状态-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return $this->responseDataJson(-1, $ex->getMessage().' | '.$ex->getLine());
        }

    }


    /**
     * 获取体验版二维码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getWxaQrcode(Request $request)
    {
        $store_id = $request->post('storeId', ''); //门店id
        $path = $request->post('path', 'pages/index/index'); //否	,指定二维码扫码后直接进入指定页面并可同时带上参数）

        try {
            if(!isset($store_id) || empty($store_id)){
                return $this->responseDataJson(202,"门店id不可为空");
            }

            $storeObj = Store::where('store_id', $store_id)
                ->where('is_close', 0)
                ->where('is_delete', 0)
                ->first();
            if (!$storeObj) {
                return $this->responseDataJson(202, "门店不存在或状态异常");
            }

            //第三方平台appid
            $component_appid = $this->app_id;

            $storeConfigAppletsInfo = DB::table("merchant_store_appid_secrets")
                ->where(['store_id' => $store_id])
                ->first();
            if( empty($storeConfigAppletsInfo) || !$storeConfigAppletsInfo ){
                return $this->responseDataJson(202, "请先完善小程序信息");
            }
            if( empty($storeConfigAppletsInfo->wechat_appid) || empty($storeConfigAppletsInfo->wechat_secret) ){
                return $this->responseDataJson(202, "请先完善小程序appid和secret密钥信息");
            }

            $customerAppletsAuthorizeAppid = DB::table($this->customerAppletsAuthorizeAppid)
                ->where([
                    't_appid' => $component_appid,
                    'AuthorizerAppid' => $storeConfigAppletsInfo->wechat_appid
                ])
                ->first();
            if( empty($customerAppletsAuthorizeAppid) || !$customerAppletsAuthorizeAppid ){
                return $this->responseDataJson(202, "该小程序未授权成功，不可上传代码");
            }
            if( empty($customerAppletsAuthorizeAppid->authorizer_refresh_token) ){
                return $this->responseDataJson(202, "该小程序授权时，authorizer_refresh_token刷新令牌为空");
            }

            $authorizerTokenResult = $this->getAuthorizerToken($component_appid, $storeConfigAppletsInfo->wechat_appid, $customerAppletsAuthorizeAppid->authorizer_refresh_token);
            if($authorizerTokenResult['status'] == 200) {
                $authorizer_access_token = $authorizerTokenResult['data']['authorizer_access_token']; //第三方平台接口调用令牌authorizer_access_token
                //再次更新刷新令牌
                if( isset($authorizerTokenResult['data']['authorizer_refresh_token']) && !empty($authorizerTokenResult['data']['authorizer_refresh_token']) ){
                    //更新该授权方 appid的authorizer_refresh_token
                    $updateRefreshToken = DB::table($this->customerAppletsAuthorizeAppid)
                        ->where([
                            't_appid' => $component_appid,
                            'AuthorizerAppid' => $storeConfigAppletsInfo->wechat_appid
                        ])
                        ->update([
                            'authorizer_refresh_token' => $authorizerTokenResult['data']['authorizer_refresh_token'],
                            'updated_at' => date("Y-m-d H:i:s", time())
                        ]);
                    if(!$updateRefreshToken){
                        return $this->responseDataJson(202, "更新authorizer_refresh_token刷新令牌失败");
                    }
                }

                if($path){
                    $path = urlencode($path);
                }
                $url = "https://api.weixin.qq.com/wxa/get_qrcode?access_token=".$authorizer_access_token.'&path='.$path;
                $resData = $this->curl_get($url);

                $result = json_decode($resData, true);
                Log::info('获取体验版二维码-结果');
                Log::info($result);
                if( isset($result['errcode']) ){
                    if ($result['errcode'] == 0) {
                        return $this->responseDataJson(200, '成功', $result);
                    }
                    else {
                        return $this->responseDataJson($result['errcode']);
                    }
                } else {
                    return $this->responseDataJson(202, 'unknown');
                }
            }

        } catch (\Exception $ex) {
            Log::info('-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }
    
    
}
